import org.apache.calcite.jdbc.CalciteConnection;
import org.apache.calcite.plan.hep.HepPlanner;
import org.apache.calcite.plan.hep.HepProgram;
import org.apache.calcite.plan.hep.HepProgramBuilder;
import org.apache.calcite.rel.RelNode;
import org.apache.calcite.rel.RelRoot;
import org.apache.calcite.rel.rules.SubQueryRemoveRule;
import org.apache.calcite.schema.SchemaPlus;
import org.apache.calcite.sql.SqlNode;
import org.apache.calcite.sql.parser.SqlParser;
import org.apache.calcite.tools.FrameworkConfig;
import org.apache.calcite.tools.Frameworks;
import org.apache.calcite.tools.Planner;

import java.sql.Connection;
import java.sql.DriverManager;
import java.util.Properties;

public class ParserTest {
    public static void main(String[] args) throws Exception {
        String sql = "";
        // 初始化配置
        SqlParser.ConfigBuilder configBuilder = SqlParser.configBuilder();
      //  configBuilder.setUnquotedCasing(Casing.UNCHANGED);
//Sql解析：解析Sql语句，通过JavaCC解析成AST语法树，表现为SqlNode
        SqlParser sqlParser = SqlParser.create(sql, configBuilder.build());
        SqlNode sqlNode = sqlParser.parseQuery();
//Sql校验：结合元数据信息验证Sql是否符合规范
        // 2.构建Connection
        // 2.1 设置连接参数
        Properties info = new Properties();
        // 不区分sql大小写
        info.setProperty("caseSensitive", "false");
        // 2.2 获取标准的JDBC Connection
        Connection jdbcConnection = DriverManager.getConnection("jdbc:calcite:", info);
        // 2.3 获取Calcite封装的Connection
        CalciteConnection connection = jdbcConnection.unwrap(CalciteConnection.class);
       // CalciteConnection connection = (CalciteConnection) DriverManager.getConnection("jdbc:calcite:model="+jsonFile, info);
        final SchemaPlus schema = connection.getRootSchema().getSubSchema("solr");
        Frameworks.ConfigBuilder builder = Frameworks.newConfigBuilder().defaultSchema(schema).parserConfig(SqlParser.configBuilder().setCaseSensitive(false).build());
        FrameworkConfig config = builder.build();

        Planner planner = Frameworks.getPlanner(config);
        SqlNode node = planner.validate(sqlNode);
//Sql查询优化：将SqlNode转换为LogicalPlan，表现为RelNode
        RelRoot relRoot = planner.rel(node);
        RelNode project = relRoot.project();
//指定优化规则
        /*
        final HepProgram program = new HepProgramBuilder()
                .addRuleInstance(SubQueryRemoveRule.PROJECT)
                .addRuleInstance(SubQueryRemoveRule.FILTER)
                .addRuleInstance(SubQueryRemoveRule.JOIN)
                .build();
//生成优化后的RelNode
        HepPlanner prePlanner = new HepPlanner(program);
        prePlanner.setRoot(project);
        RelNode relNode = prePlanner.findBestExp();
        */
//ToDo 执行查询

    }
}
